package eightDataType;

import org.junit.Test;

/**
 * @author Ajie
 * @date 11/30/21
 * @function 结论：
 * //char[]-->string
 * //string-->byte[]
 * //byte[]-->string
 *  strFromChars.equals(strFromBytes):true  数据内容相等。无论是否 FF
 */
public class CharUtil {

    @Test
    public void testByteToHex(){
        char[] data = new char[]{0x01, 0x05, 0x00, 0x02, 0xFF, 0x00, 0x2D,  0xFA};
        System.out.println("byte: "+new String(data));
        //char[]-->string
        String strFromChars = charsToHex(data);
        System.out.println("testcharsToHex:"+ strFromChars);

        //string-->byte[]
        byte[] bytes = ByteUtil.hexStrToBytes(strFromChars);
        //byte[]-->string
        String strFromBytes = ByteUtil.bytesToHex(bytes);
        System.out.println("bytesToHex    :"+strFromBytes);
        System.err.println("strFromChars.equals(strFromBytes):"+strFromChars.equals(strFromBytes));
    }

    /**
     * char[]数组转16进制 String
     * @param chars 需要转换的byte数组
     * @return  转换后的Hex字符串
     */
    public static String charsToHex(char[] chars) {
        StringBuffer sb = new StringBuffer();
        for(int i = 0; i < chars.length; i++) {
            String hex = Integer.toHexString(chars[i] & 0xFF);
            if(hex.length() < 2){
                sb.append(0);
            }
            sb.append(hex);
        }
        return sb.toString();
    }

}
